package com.ruoyi.equip.vert.config;


import cn.hutool.core.util.HexUtil;
import com.google.common.collect.Maps;
import com.ruoyi.equip.vert.parser.DataReader;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class TcpServerVerticle extends AbstractVerticle
{
    public final static Map<String, NetSocket> CLIENT_MAP = Maps.newHashMap();

    private NetServer netServer;

    @Override
    public void start()
    {

        netServer = vertx.createNetServer(
                new NetServerOptions().setHost("192.168.1.111")
                        .setPort(11122));

        // 处理连接请求
        netServer.connectHandler(socket ->
        {

            String handlerID = socket.writeHandlerID();
            CLIENT_MAP.put(handlerID, socket);
            // 接收客户端发送的消息
            socket.handler(buff ->
            {
                DataReader.decodeReader(buff, handlerID);
            });


            // 监听客户端的退出连接
            socket.closeHandler(close ->
            {
                CLIENT_MAP.remove(socket.writeHandlerID());
                log.error("客户端退出连接：{} ", socket.writeHandlerID());
            });
        });


        // 监听端口
        netServer.listen(11122, "192.168.1.111", res ->
        {
            if (res.succeeded()) {
                log.info(" 服务器启动成功");
            } else {
                log.error(" 服务器启动失败 {}", res.cause().getMessage());
            }
        });
    }

    public void sendMsg(String handlerID, String sendMsg)
    {
        log.info("TCP SEND:{}", sendMsg);
        NetSocket socket = TcpServerVerticle.CLIENT_MAP.get(handlerID);
        if (socket != null)
            socket.write(Buffer.buffer(HexUtil.decodeHex(sendMsg)), resp ->
            {
                if (resp.succeeded()) {
                    log.info("服务端 发送消息成功 {}", sendMsg);
                } else {
                    log.error("发送消息失败");
                }
            });
    }

}
